package com.dz.lm.common.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.dz.lm.common.utils.StringUtils;
import com.dz.lm.common.utils.json.JsonUtils;
import com.dz.lm.common.utils.random.RandomUtils;

@Component
public class IMessage {
	private static final Logger logger = LoggerFactory.getLogger(IMessage.class);
	private static InputStream in;
	private static Properties p;
	static {
		try {
			in = IMessage.class.getClassLoader().getResourceAsStream("im_info.properties");
			p = new Properties();
			p.load(in);
		} catch (FileNotFoundException e) {
			logger.error("IMessage Not Found File :im_info.properties");
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("IMessage IOException");
			e.printStackTrace();
		}
	}

	/**
	 * 获取融云token
	 * 
	 * @param userId
	 * @param userName
	 * @param userProfile
	 * @return
	 * @throws Exception
	 */
	public String getToken(String userId, String userName, String userProfile) throws Exception {
		// 发送内容
		String url = p.getProperty("ryUrl");
		String appkey = p.getProperty("ryAppkey");
		String appSecret = p.getProperty("ryAppSecret");
    	String token = null;
    	
    	String nonce = RandomUtils.generateNumString(8);
    	Date day = new Date();
    	String timestamp = String.valueOf(day.getTime());
    	String signature = appSecret + nonce + timestamp;
    	signature = DigestUtils.sha1Hex(signature.getBytes());
		PostMethod postMethod = new PostMethod(url + "?nonce=" + nonce + "&signTimestamp=" + timestamp + "&signature=" + signature);
		try {
			postMethod.getParams().setContentCharset("UTF-8");
			postMethod.addRequestHeader("Connection", "close");
			postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			postMethod.addRequestHeader("App-Key", appkey);
			postMethod.addRequestHeader("Nonce", nonce);
			postMethod.addRequestHeader("Timestamp", timestamp);
			postMethod.addRequestHeader("Signature", signature);
			NameValuePair[] data = {
			        new NameValuePair("userId", MD5Util.MD5(userId)),
			        new NameValuePair("name", userName),
			        new NameValuePair("portraitUri", userProfile)
			};
			postMethod.setRequestBody(data);
			HttpClient httpClient = new HttpClient();
			int statusCode = httpClient.executeMethod(postMethod);
			String response = postMethod.getResponseBodyAsString();
			logger.info("getToken statusCode: " + statusCode + ", body: "+ response);
			
			if(200 == statusCode && !StringUtils.isEmpty(response)){
				Map<String, Object> param = JsonUtils.readValue(response);
				if ("200".equals(param.get("code").toString())) {
					token = param.get("token").toString();
				} else {
					logger.info("融云返回错误"+response);
				}
			}else{
				throw new Exception("融云返回结果解析错误");
			}
		} catch (Exception e) {
			logger.info("融云返回错误" + e.getStackTrace());
			throw new Exception("融云返回错误", e);
		} finally {
			// 释放连接
			postMethod.releaseConnection();
		}
        return token;
	}	
}
